package cn.tedu.yushougeproduct.service.impl;

import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.util.PageInfoToPageDataConverter;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushougeproduct.mapper.*;
import cn.tedu.yushougeproduct.pojo.entity.*;
import cn.tedu.yushougeproduct.pojo.param.SpuAddNewParam;
import cn.tedu.yushougeproduct.pojo.param.SpuUpdateInfoParam;
import cn.tedu.yushouge.commons.pojo.vo.PageData;
import cn.tedu.yushougeproduct.pojo.vo.*;
import cn.tedu.yushougeproduct.service.ISpuService;
import cn.tedu.yushougeproduct.util.IdUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class SpuServiceImpl implements ISpuService {

    public SpuServiceImpl() {
        log.info("创建业务对象：SpuServiceImpl");
    }

    @Autowired
    private IdUtils idUtils;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Override
    public void addNew(SpuAddNewParam spuAddNewParam) {
        log.debug("开始处理【新增SPU】的业务，参数：{}", spuAddNewParam);
        // 检查品牌：是否存在，是否启用
        Long brandId = spuAddNewParam.getBrandId();
        BrandStandardVO brand = brandMapper.getStandardById(brandId);
        if (brand == null) {
            String message = "新增SPU失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查类别：是否存在，是否启用，是否不包含子级
        Long categoryId = spuAddNewParam.getCategoryId();
        CategoryStandardVO category = categoryMapper.getStandardById(categoryId);
        if (category == null) {
            String message = "新增SPU失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (category.getEnable() == 0) {
            String message = "新增SPU失败，类别已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查相册：是否存在
        Long albumId = spuAddNewParam.getAlbumId();
        AlbumStandardVO album = albumMapper.getStandardById(albumId);
        if (album == null) {
            String message = "新增SPU失败，相册数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 获取SPU ID
        Long spuId = idUtils.generateSpuId();

        // 创建SPU对象
        Spu spu = new Spu();
        // 复制属性值
        BeanUtils.copyProperties(spuAddNewParam, spu);
        spu.setId(spuId);
        spu.setBrandName(brand.getBrandName());
        spu.setCategoryName(category.getCategoryName());
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);
        spu.setIsPublished(0);
        spu.setGmtCreate(LocalDateTime.now());
        // 插入SPU数据
        int rows = spuMapper.insert(spu);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 创建SpuDetail对象
        SpuDetail spuDetail = new SpuDetail();
        // 补全属性值：spu_id >>> 与以上Spu的ID相同
        spuDetail.setSpuId(spuId);
        // 补全属性值：detail >>> 来自参数
        spuDetail.setDetail(spuAddNewParam.getDetail());
        // 插入SpuDetail数据
        rows = spuDetailMapper.insert(spuDetail);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void setPublished(Long id) {
        log.debug("开始处理【上架spu】的业务，参数：{}", id);
        updatePublishedById(id, 1);

        Spu spu = new Spu();
        spu.setId(id);
        spu.setGmtModified(LocalDateTime.now());
        spuMapper.updateById(spu);
    }

    @Override
    public void setNotPublished(Long id) {
        log.debug("开始处理【下架spu】的业务，参数：{}", id);
        updatePublishedById(id, 0);

        Spu spu = new Spu();
        spu.setId(id);
        spu.setGmtModified(LocalDateTime.now());
        spuMapper.updateById(spu);
    }

    @Override
    public void updateInfoById(Long id, SpuUpdateInfoParam spuUpdateInfoParam) {
        log.debug("开始处理【修改spu详情】的业务，ID：{}，新数据：{}", id, spuUpdateInfoParam);

        QueryWrapper<Spu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = spuMapper.selectCount(queryWrapper);
        log.debug("根据spuID统计匹配的spu数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改spu详情失败，spu数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        QueryWrapper<Spu> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", spuUpdateInfoParam.getName())
                .ne("id", id);
        int countByName = spuMapper.selectCount(queryWrapper2);
        log.debug("根据spu名称统计匹配的spu数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改spu详情失败，spu名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Spu spu = new Spu();
        BeanUtils.copyProperties(spuUpdateInfoParam, spu);
        spu.setId(id);
        spu.setGmtModified(LocalDateTime.now());
        int rows = spuMapper.updateById(spu);
        if (rows != 1){
            String message = "修改spu失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的spu数据更新入到数据库，完成！");
    }

    private void updatePublishedById(Long id , Integer published){
        SpuStandardVO currentSpu = spuMapper.getStandardById(id);

        if (currentSpu == null) {
            String message = PUBLISHED_TEXT[published] + "spu失败，spu数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (currentSpu.getIsPublished() == published) {
            String message = PUBLISHED_TEXT[published] + "spu失败，此spu已经处于" + PUBLISHED_TEXT[published] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Spu updateSpu = new Spu();
        updateSpu.setId(id);
        updateSpu.setIsPublished(published);

        int rows = spuMapper.updateById(updateSpu);
        if (rows != 1) {
            String message = PUBLISHED_TEXT[published] + "spu失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public SpuStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询SPU详情】的业务，参数：{}", id);
        SpuStandardVO queryResult = spuMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "根据ID查询SPU详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将返回SPU详情：{}", queryResult);
        return queryResult;
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询SPU列表】的业务，页码：{}", pageNum);
        return list(pageNum,5);
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询SPU列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<SpuListItemVO> list = spuMapper.list();
        PageInfo<SpuListItemVO> pageInfo= new PageInfo<>(list);
        PageData<SpuListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public PageData<SpuListItemVO> listByBrandId(Integer pageNum, Long brandId) {
        log.debug("开始处理【根据品牌ID查询SPU列表】的业务，页码：{}，每页记录数：{}", pageNum, 5);
        PageHelper.startPage(pageNum,5);
        List<SpuListItemVO> list = spuMapper.listByBrandId(brandId);
        PageInfo<SpuListItemVO> pageInfo= new PageInfo<>(list);
        PageData<SpuListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public PageData<SpuListItemVO> listByCategoryId(Integer pageNum, Long categoryId) {
        log.debug("开始处理【根据品牌ID查询SPU列表】的业务，页码：{}，每页记录数：{}", pageNum, 10);
        PageHelper.startPage(pageNum,10);
        List<SpuListItemVO> list = spuMapper.listByCategoryId(categoryId);
        PageInfo<SpuListItemVO> pageInfo= new PageInfo<>(list);
        PageData<SpuListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public List<SpuListItemVO> listByKeywords(String keywords) {
        log.debug("开始处理【根据关键字查询SPU列表】的业务");
        List<SpuListItemVO> list = spuMapper.listByKeywords(keywords);
        log.debug("查询完成，即将返回：{}",list);
        return list;
    }
}
